#!/usr/bin/env python
from XmlTools import SMKernel, XmlFunc

def doNothing(infile, outfile=None, sort=False):
    if outfile is None:
        outfile = '.'.join(infile.split('.')[:-1]+'_new.xml')

    XmlFunc.doNothing(infile, outfile, sort)

def makeSedXml(infile, outfile=None):
    if outfile is None:
        outfile = '.'.join(infile.split('.')[:-1]+'_sed.xml')

    XmlFunc.freeze_index(infile, outfile)

def classifyDiffusePoint(infile, outfile=None):
    if outfile is None:
        outpfx = '.'.join(outfile.split('.')[:-1])
    else:
        outpfx = outfile

    XmlFunc.classifyPsExt(infile, outpfx)

def makeTSXml(infile, outfile=None):
    if outfile is None:
        outfile = '.'.join(outfile.split('.')[:-1]) + '_tsmap.xml'

    XmlFunc.freeze_allButIemIso(infile, outfile)

def classifyFreeFix(infile, outfile=None):
    if outfile is None:
        outpfx = '.'.join(outfile.split('.')[:-1])
    else:
        outpfx = outfile

    XmlFunc.classifyFreeFix(infile, outpfx)

def copyFreeFix(infile, outfile):
    XmlFunc.copyFreeFix(outfile, infile, outfile)

def replaceExpCutoff(infile, outfile):
    XmlFunc.replaceExpCutoff(infile, outfile)

def makeRegion(infile, outfile):
    x = SMKernel.SourceModel(infile, raiseErr=True)
    x.makeRegion(outfile)

def makeFreeRegion(infile, outfile):
    x = SMKernel.SourceModel(infile, raiseErr=True)
    xfr = SMKernel.SourceModel(raiseErr=False)
    for src in x.srcList.values():
        if src.isfree:
            xfr[None] = src
    xfr.makeRegion(outfile)


def cli():
    import argparse
    helpString = 'Freeze index of the sources'
    parser = argparse.ArgumentParser(description=helpString)
    parser.add_argument("infile", type=str, help="input xml file")
    parser.add_argument("outfile", type=str, help="output xml file")
    parser.add_argument("-job", type=str, default='S', choices=['N', 'S', 'T', 'C', 'E', 'CF', 'CD', 'R', 'RF'],
           help="N=Nothing, S=makeSedXml(default), T=makeTSXml, C=copyFreeFix, CF=classifyFreeFix, CD=classifyDiffusePoint, R=makeRegion, RF=makeFreeRegion")

    args = parser.parse_args()

    if args.job == 'N':
        doNothing(args.infile, args.outfile, True)
    elif args.job == 'S':
        makeSedXml(args.infile, args.outfile)
    elif args.job == 'T':
        makeTSXml(args.infile, args.outfile)
    elif args.job == 'C':
        copyFreeFix(args.infile, args.outfile)
    elif args.job == 'E':
        replaceExpCutoff(args.infile, args.outfile)
    elif args.job == 'CF':
        classifyFreeFix(args.infile, args.outfile)
    elif args.job == 'CD':
        classifyDiffusePoint(args.infile, args.outfile)
    elif args.job == 'R':
        makeRegion(args.infile, args.outfile)
    elif args.job == 'RF':
        makeFreeRegion(args.infile, args.outfile)
    else:
        raise NotImplementedError(args.job)

if __name__ == '__main__': cli()
